# encoding: utf-8
# @File  : users.py
# @Author: shaoyun
# @Date  :  2025/05/11
import uuid

from fastapi import APIRouter, Depends, Path
from sqlalchemy.orm import Session
from starlette.status import HTTP_201_CREATED

from app.api.dependencies import get_current_user, admin_required, get_db
from app.core.response import get_response
from app.core.security import get_password_hash
from app.core.status_codes import (
    SUCCESS, ERROR, USERNAME_NOT_EXIST, PERMISSION_DENIED
)
from app.models.user import User, UserRole
from app.schemas.user import UserCreate, UserUpdate

router = APIRouter()


def user_to_dict(user: User) -> dict:
    """将 User 模型转换为字典"""
    return {
        "id": user.id,
        "username": user.username,
        "email": user.email,
        "role": user.role.value,
        "is_active": user.is_active,
        "created_at": user.created_at
    }


def update_user_fields(user: User, user_update: UserUpdate, db: Session):
    """
    更新用户的字段
    :param user: User 实例
    :param user_update: UserUpdate 数据
    :param db: 数据库会话
    """
    if user_update.username and user_update.username != user.username:
        if db.query(User).filter(User.username == user_update.username).first():
            return get_response(USERNAME_NOT_EXIST)

    if user_update.email and user_update.email != user.email:
        if db.query(User).filter(User.email == user_update.email).first():
            return get_response(ERROR, "Email already registered")

    if user_update.username:
        user.username = user_update.username
    if user_update.email:
        user.email = user_update.email
    if user_update.password:
        user.hashed_password = get_password_hash(user_update.password)
    if user_update.role:
        user.role = UserRole(user_update.role)
    if user_update.is_active is not None:
        user.is_active = user_update.is_active

    return None


@router.post("/create", response_model=dict, status_code=HTTP_201_CREATED)
async def create_user(
        user_in: UserCreate,
        db: Session = Depends(get_db),
        current_user: User = Depends(admin_required)
):
    """创建新用户（仅管理员）"""
    if db.query(User).filter(User.username == user_in.username).first():
        return get_response(USERNAME_NOT_EXIST)

    if db.query(User).filter(User.email == user_in.email).first():
        return get_response(ERROR, "Email already registered")

    user = User(
        id=str(uuid.uuid4()),
        username=user_in.username,
        email=user_in.email,
        hashed_password=get_password_hash(user_in.password),
        role=UserRole(user_in.role) if user_in.role else UserRole.USER
    )
    db.add(user)
    db.commit()
    db.refresh(user)

    return get_response(SUCCESS, user_to_dict(user))


@router.get("/list", response_model=dict)
async def get_users(
        skip: int = 0,
        limit: int = 100,
        db: Session = Depends(get_db),
        current_user: User = Depends(admin_required)
):
    """获取用户列表（仅管理员）"""
    users = db.query(User).offset(skip).limit(limit).all()
    user_list = [user_to_dict(user) for user in users]
    return get_response(SUCCESS, user_list)


@router.get("/me/info", response_model=dict)
async def get_current_user_info(
        current_user: User = Depends(get_current_user)
):
    """获取当前用户信息"""
    return get_response(SUCCESS, user_to_dict(current_user))


@router.get("/me/tasks", response_model=dict)
async def get_current_user_tasks(
        skip: int = 0,
        limit: int = 100,
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user)
):
    """获取当前用户的任务列表"""
    tasks = current_user.tasks
    sorted_tasks = sorted(tasks, key=lambda x: x.created_at, reverse=True)
    paginated_tasks = sorted_tasks[skip:skip + limit]

    task_list = [
        {
            "id": task.id,
            "name": task.name,
            "status": task.status.value,
            "created_at": task.created_at,
            "finished_at": task.finished_at
        }
        for task in paginated_tasks
    ]

    return get_response(SUCCESS, {
        **user_to_dict(current_user),
        "tasks": task_list
    })


@router.get("/{user_id}/detail", response_model=dict)
async def get_user(
        user_id: str = Path(...),
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user)
):
    """获取用户详情"""
    is_admin = current_user.role == UserRole.ADMIN
    is_self = user_id == current_user.id

    if not (is_admin or is_self):
        return get_response(PERMISSION_DENIED)

    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        return get_response(USERNAME_NOT_EXIST)

    return get_response(SUCCESS, user_to_dict(user))


@router.put("/me/update", response_model=dict)
async def update_current_user(
        user_update: UserUpdate,
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user)
):
    """更新当前用户信息"""
    error_response = update_user_fields(current_user, user_update, db)
    if error_response:
        return error_response

    db.commit()
    db.refresh(current_user)

    return get_response(SUCCESS, user_to_dict(current_user))


@router.put("/{user_id}", response_model=dict)
async def update_user(
        user_update: UserUpdate,
        user_id: str = Path(...),
        db: Session = Depends(get_db),
        current_user: User = Depends(admin_required)
):
    """更新用户信息（仅管理员）"""
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        return get_response(USERNAME_NOT_EXIST)

    error_response = update_user_fields(user, user_update, db)
    if error_response:
        return error_response

    db.commit()
    db.refresh(user)

    return get_response(SUCCESS, user_to_dict(user))